<?php
abstract class Library extends Object
{
	public $path = '';
	public $smarty = null;
	public $table_name = null;
	private $file_not_exist = array();
	private $array_variable = array();
	private $current_dir = -1;
	public $database = null;
	public $error_message = '';
	public $error_no = 0;
	private $template;
	private $relations = array();
	
	
//	public function __construct()
//	{
//		$this->template = new Template();
//	}
//	
	public function error_occur($error_type )
	{
		switch ($error_type)
		{
			case RECORD_EXIST:
				$this->error_no = RECORD_EXIST;
				$this->error_message = '已经存在';
				break;
		}
	}
	
	public function initialize()
	{
		$this->path = strtolower($this->path);
		$this->smarty = new Smarty();
		$this->smarty->template_dir	= WEBROOT.SITE_RELATIVE.'modules'.DIRECTORY_SEPARATOR.$this->path;
		$this->smarty->cache_dir	= WEBROOT.SITE_RELATIVE.'cache'.DIRECTORY_SEPARATOR.'template'.DIRECTORY_SEPARATOR.'smarty'.DIRECTORY_SEPARATOR.$this->path;
		//为集中起见，将下面两行替换成下面的三四行
		$this->smarty->config_dir	= $this->get_template_directory('module');
		$this->smarty->compile_dir	= PATH_SITE.SITE_RELATIVE.'cache'.DIRECTORY_SEPARATOR.'template'.DIRECTORY_SEPARATOR.'smarty'.DIRECTORY_SEPARATOR.'template_c'.DIRECTORY_SEPARATOR;;
		$this->smarty->config_dir	= PATH_SITE.SITE_RELATIVE.'setting'.DIRECTORY_SEPARATOR.'configs'.DIRECTORY_SEPARATOR;
		
		$this->smarty->left_delimiter	="<!--# ";
		$this->smarty->right_delimiter	= "; #-->";
		
		$this->smarty->allow_php_tag	= true;
		
		$this->smarty->caching	= false;
		
		$this->template = Helper::instance('Template');
		
		$this->database = new Database();
	}
	
	protected function add_relation(Relation $relation)
	{
		$this->relations[str_replace('.', '', $relation->library)] = $relation;
	}
	
	function __get($class_name)
	{
		if (isset($this->relations[$class_name]))
		{
			$obj_relation = $this->relations[$class_name];
			
			if( $obj_relation->ref == null ){
				$this->ref = Library::instance($obj_relation->library)->find_by_relation($this, $obj_relation->relations);
			}
			return $this->ref;
		}
		
		die('Cannot find the property: '.$class_name);
	}
	
	private function find_by_relation(&$obj_master, $relations)
	{
		$condition = '';
		
		foreach($relations as $key=>$value)
		{
			//$condition .= " and {$table_master}.{$key}={$this->table_name}.{$value}";
			$condition .= " and {$value}='{$obj_master->$key}'";
		}
		$condition = trim($condition, ' and');
		$sql = "select * from {$this->table_name}
				where ".$condition;
		
		return $this->database->query($sql);
	}
	
	private function get_template_directory($type='')
	{
		global $smarty;
		$this->path = strtolower($this->path);
		$dir = array();
		//
		if( defined('WEB_POSITION') ) {
			//当前主题下的模板
			if( SITE_THEME != 'default' ) {
				$dir['theme'] = WEBROOT.SITE_RELATIVE.'modules'.DIRECTORY_SEPARATOR.$this->path.'themes'.DIRECTORY_SEPARATOR.SITE_THEME.DIRECTORY_SEPARATOR.WEB_POSITION.DIRECTORY_SEPARATOR;
			}
			//默认default模板
			$dir['defult'] = WEBROOT.SITE_RELATIVE.'modules'.DIRECTORY_SEPARATOR.$this->path.'themes'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.WEB_POSITION.DIRECTORY_SEPARATOR;
		}
		
		//原始的模板（已不再使用）
		$dir['module'] = WEBROOT.SITE_RELATIVE.'modules'.DIRECTORY_SEPARATOR.$this->path;
		//可放在统一的目录下（待设置）
		//$dir['themes'] = $smarty->template_dir.$this->path.WEB_POSITION.DIRECTORY_SEPARATOR;
		
		if( !empty($type) ) {
			return $dir[$type];
		}
		
		return $dir;
	}
	
	//get rows count by condition
	public function getListCount($condition='')
	{
		$sql = "select count(id) as NUM
				from {$this->table_name}
				where 1=1 ". $condition;
		
		return $this->database->GetNum($sql);
	}
	
	//get list of rows by condition
	public function getList($condition='', $order='', $limit='')
	{
		$sql = "select *
				from {$this->table_name}
				where 1=1 $condition $order $limit";
		//echo $sql;
		//die(var_dump($this->database));
		return $this->database->query($sql);
	}
	
	public function lockOption($cbRowChecked)
	{
		if( is_array($cbRowChecked)){
			$cbRowChecked = implode(",", $cbRowChecked);
		}
		$sql = "update {$this->table_name}
					set Status='3005002'
				where id in(".$cbRowChecked.")";
		//echo($sql);
		return $this->database->edit($sql);
	}

	public function unlockOption($cbRowChecked)
	{
		if( is_array($cbRowChecked)){
			$cbRowChecked = implode(",", $cbRowChecked);
		}
		$sql = "update {$this->table_name}
					set Status='3005001'
				where id in(".$cbRowChecked.")";
		//echo($sql);
		return $this->database->edit($sql);
	}
	
	function __call($method, $args)
	{
		$args = $this->database->injection_strict($args);
		$method_new = preg_replace('/tempcode/i', 'id', $method);
		
		if (false !== ($pos=strpos($method_new, 'get_info_by_'))) {
			return $this->database->query("
				select *
				from {$this->table_name}
				where ".str_replace('get_info_by_', '', $method_new)." = '{$args[0]}'");
		} elseif(false !== ($pos=strpos($method_new, 'exist_'))) {
			$sql = "select count(id) as NUM
					from {$this->table_name}
					where ".str_replace('get_info_by_', '', $method_new)." = '{$args[0]}'";
			
			$result = $this->database->GetNum($sql);
			return ($result>0)? true: false;
		} elseif(false != preg_match_all("/^get_(.*?)_by_(.*?)$/", $method_new, $array_check, PREG_SET_ORDER)) {//get_Account_id_by_id(from member table)
			$return_field = $array_check[0][1];
			$where_field = $array_check[0][2];
			
			//WatchDog::screen_sql();
			$objs_temp = $this->database->query("
				select {$return_field}
				from {$this->table_name}
				where {$where_field} = '{$args[0]}'");
			
			if(!empty($objs_temp)){
				return $objs_temp[0]->$return_field;
			} else {
				return 0;
			}
		}
		
		die('Cannot find method '+$method);
	}
	
	function deleteOption($cbRowChecked)
	{
		if( is_array($cbRowChecked)){
			$cbRowChecked = implode(",", $cbRowChecked);
		}
		$sql = "update {$this->table_name}
					set Status='3'
				where id in(".$cbRowChecked.")";
		//echo($sql);
		return $this->database->edit($sql);
	}
	
//	public function get_call_class()
//	{
//		//$bt = debug_backtrace();
//		//$x = $bt[0]['object'];
//		//return get_class($x);
//		return get_class($this);
//	}
	
	public function assign($var_name, $var_value)
	{
		$this->array_variable[$var_name] = $var_value;
	}
	
	public function getfile($file='list', $is_required = true, $file_extension='.htm')
	{
		$this->template->file_not_exist = array();
		global $template;
		//die(var_dump($file_extension));
		
		$library_name = get_class($this);
//		if(version_compare(PHP_VERSION, '5.3', '>=') ){
//			$library_name = get_called_class();
//		} else {
//			$library_name = $this->get_call_class();
//		}
		$library_name = str_replace('Lib_', '', $library_name);
		
		$tplname = $library_name.'_'.$file;
		
		if($this->get_smarty_file($tplname)) {
			return true;
		} elseif($file = $this->get_self_defined_file($tplname, $is_required, $file_extension)) {
			if( $is_required ) {
				return true;
			} else {
				//die($file);
				return $file;
			}
		}
		//die(var_dump($template));
		$this->template->show_errors();
	}
	
	function get_file($file_name)
	{
		$template_dir = $this->get_template_directory();
		foreach ($template_dir as $key=>$value ){
			$tplfile = $value.trim(trim($file_name, DIRECTORY_SEPARATOR), '/');
			
			if(!file_exists($tplfile)) {
				$this->template->file_not_exist[] = $tplfile;
				$tplfile = '';
				continue;
			}
			break;
		}
		
		if( empty($tplfile) )
		{
			$this->template->show_errors();
		} else {
			return str_replace('\\', '/', str_replace(WEBROOT.SITE_RELATIVE, '/', $tplfile));
		}
	}
	
	private function get_self_defined_file($tplname, $is_required, $file_extension)
	{
		$cachefile = '';
		if( $file_extension == '' ){
			$file_extension = '.htm';
		}
		
		$tplfile = '';
		
		$template_dir = $this->get_template_directory();
		
		foreach ($template_dir as $key=>$value ){
			$tplfile = $value.$tplname.$file_extension;
			
			if(!file_exists($tplfile)) {
				$this->template->file_not_exist[] = $tplfile;
				$tplfile = '';
				continue;
			}
			break;
		}
		
		if( $tplfile == ''){
			return false;
		}
		//die($tplfile);
		$cachefile .= WEBROOT.SITE_RELATIVE.'cache'.DIRECTORY_SEPARATOR.'template'.DIRECTORY_SEPARATOR.'self_defined'.DIRECTORY_SEPARATOR.$this->path;
		//die($cachefile);
		
		if( !file_exists($cachefile)){
			$helper_File = Helper::instance('File');
			$helper_File->createFolder($cachefile);
			//die($tplfile);
		}
		
		if( $is_required ) {
			extract($this->array_variable);
			require $this->template->cacheFile($tplname, $tplfile, $cachefile);
			$this->array_variable = array();
		} else {
			if( $file_extension == '.xml') {
				return $tplfile;
			}
			return $this->template->cacheFile($tplname, $tplfile, $cachefile);
		}
		
		return true;
	}
	
	private function get_smarty_file($tplname, $file_extension='.tpl')
	{
		$template_dir = $this->get_template_directory();
		
		foreach ($template_dir as $key=>$value ){
			$tplfile = $value.$tplname.$file_extension;
			
			if(!file_exists($tplfile)) {
				$this->template->file_not_exist[] = $tplfile;
				$tplfile = '';
				continue;
			}
			$this->smarty->template_dir = $value;
			$this->smarty->display($tplname.'.tpl');
			return true;
		}
		
		return false;
	}
	
	function content($file='list')
	{
		ob_start();
		require $this->getfile($file);
		//require $file;
		$out1 = ob_get_contents();
		ob_end_clean();
		return $out1;
	}
	
	static function instance($libraryName)
	{
		$file_not_exist = array();
		$array_library = explode('.', $libraryName);
		$library_name = str_replace('.', '', $libraryName);
		
		if(file_exists(PATH_LIBRARY."Lib_".$library_name.EXT)){
			require_once(PATH_LIBRARY."Lib_".$library_name.EXT);
			$script = '$library =  new Lib_'.$library_name."();";
			$script .= '$library->path = "'.str_replace("\\", "\\\\", $library_name.DIRECTORY_SEPARATOR).'";';
			eval($script);
			$library->initialize();
			//$library->objects = array();
			return $library;
		}
		$file_not_exist[] = PATH_LIBRARY."Lib_".$library_name.EXT;
		
		$folder_name = '';
		
		if( count($array_library) > 1) {
			$folder_name = strtolower($array_library[0]).DIRECTORY_SEPARATOR;
		} else {
			$folder_name = strtolower($library_name).DIRECTORY_SEPARATOR;
		}
		//echo(WEBROOT.SITE_RELATIVE.'modules'.DIRECTORY_SEPARATOR.$folder_name."Lib_".$library_name.EXT);
		if(file_exists(WEBROOT.SITE_RELATIVE.'modules'.DIRECTORY_SEPARATOR.$folder_name."Lib_".$library_name.EXT)){
			require_once(WEBROOT.SITE_RELATIVE.'modules'.DIRECTORY_SEPARATOR.$folder_name."Lib_".$library_name.EXT);
			$script = '$library = new Lib_'.$library_name."();";
			$script .= '$library->path = "'.str_replace("\\", "\\\\", $folder_name).'";';
			eval($script);
			
			$library->initialize();
			//$library->objects = array();
			return $library;
		}

		$file_not_exist[] = WEBROOT.SITE_RELATIVE.'modules'.DIRECTORY_SEPARATOR.$folder_name."Lib_".$library_name.EXT;
		
		echo("The following library file(s) cannot be found on server:<br />");
		foreach( $file_not_exist as $key=>$val){
			echo "<b>".$val."</b> not exists!<br />";
		}
		die();
	}
	
	function getobject()
	{
		$this->objects[0]->id ='aaaa';
		return $this->objects[0];
	}
	/**
	 * 
	 * Enter description here ...
	 * @param unknown_type $array_parameters
	 * @param unknown_type $field_name
	 * , 'Member_id'=>array('!=', $obj_Task->Member_id)
	 * $this->filter($arrayParameters, 'Project_id|=');
	 */
	function filter(&$array_parameters, $field_name)
	{
		$array_field = explode('|', $field_name);
		$field_name = $array_field[0];
		$operator = $array_field[1];
		
		$condition = '';
		$prefix = '';
		$sufix = '';
		$total_prefix = ' and ';
		$total_sufix = '';
		$link = ' or ';
		$i = 0;
		
		$array_values = array();
		if(is_array($array_parameters[$field_name])) {
			//die(var_dump($array_parameters[$field_name]));
			$array_values[] = $array_parameters[$field_name][1];
			$operator = $array_parameters[$field_name][0];
			//die(print_r($array_values));
		} else {
			$array_values[] = $array_parameters[$field_name];
		}
		
		switch ($operator){
			case '=':
				$prefix = "'";
				$sufix = "'";
				break;
			case 'in':
				$prefix = "(";
				$sufix = ")";
				break;
			case 'in!=':
				$prefix = "'";
				$sufix = "'";
				
				$link = ' and ';
				//die('aaa');
				$array_values = explode(',', $array_values[0]);
				$operator = '!=';
				
				if( count( $array_values ) > 1 ){
					$total_prefix .= '(';
					$total_sufix = ')';
				}
				break;
			case 'in=':
				$prefix = "'";
				$sufix = "'";
				
				$array_values = explode(',', $array_values[0]);
				$operator = '=';
				
				if( count( $array_values ) > 1 ){
					$total_prefix .= '(';
					$total_sufix = ')';
				}
				break;
			case 'like':
				$prefix = "'%";
				$sufix = "%'";
				break;
		}
		//die($operator);
		if(isset($array_parameters[$field_name]) && $array_parameters[$field_name] !== "")
		{
			foreach ($array_values as $value) {
				if( $i > 0 ){
					$condition .= $link;
				}
				
				$condition .= '`'.$this->table_name.'`.'.$field_name.$operator.$prefix.$value.$sufix;
				$i++;
			}
			
			$condition = $total_prefix.$condition.$total_sufix;
		}
		
		return $condition;
	}
	
	function get_relation_by_fieldname( $relation_field_name, $filed_values)
	{
		$table_name = '';
		$field_name = '';
		//die(var_dump($relation_field_name));
		
		if( version_compare(PHP_VERSION, '5.3', '>=') ) {
			$table_name = strtolower(strstr($relation_field_name, '_', true));
		} else {
			$table_name = strtolower(strstr($relation_field_name, '_'));
			$table_name = str_replace($table_name, '', $relation_field_name);
		}
		//die(var_dump($table_name));
		
		$field_name = trim(strstr($relation_field_name, '_'), '_');
		//die($table_name);
		
		$parameters = array($field_name=>$filed_values);
		
		$library_name = str_replace('_', '', $table_name);
		$lib_temp = library::instance($library_name);
		$condition = $lib_temp->filter($parameters, $field_name.'|in=');
		
		$sql = "select * from {$table_name}
				where 1=1 {$condition}";
		//echo ($sql);
		return $this->database->query($sql);
	}
	
	
	function get_relation( $table_name )
	{
		
	}
}
?>